package org.tio.sitexxx.web.server.controller.minip;

import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Coupon;
import org.tio.sitexxx.service.model.main.Member;
import org.tio.sitexxx.service.service.qj.CouponService;
import org.tio.sitexxx.service.service.qj.MemberService;

import java.util.*;


@RequestPath(value ="/coupon")
public class CouponController {
    /**
     * 优惠卷部分逻辑，有点乱，我是不想去改了 本人只提供注释
     * @param type
     * @param openid
     * @return
     */
    @RequestPath(value = "/list/{type}")
    public Object getCoupon(String type,String openid){
        System.out.println("type:"+type);
        Map<String,Object> query = new HashMap<>();
        query.put("openid",openid);
//        System.out.println(openid);
        Member Member = MemberService.me.getMember(query);
        //我也不想这么写但是路由已经固定了。。
        if(type.equals("number")){ // 根据member_id获取优惠券数量

            return number(Member.getId());

        }else if(type.equals("all")){//获取用户全部优惠券

            return getCouponsByMemberId(Member.getId());

        }else {//根据type获取用户相应类型优惠券

            //这里type是int值
            return getCouponsByType(Integer.parseInt(type),Member.getId());
        }
    }

    public Map<String,Object> number(Integer id){
        Map<String,Object> resultMap = new HashMap<>();
        Map<String,Object> query = new HashMap<>();
        query.put("memberId",id);
        resultMap.put("number",CouponService.me.Count(query));
        return resultMap;
    }

    public List<Coupon> getCouponsByMemberId(Integer id){
        Map<String,Object> query = new HashMap<>();
        query.put("memberId",id);
        List<Coupon> Coupons =  CouponService.me.getCoupons(query);
        DeleteSome(Coupons);
        return Coupons;
    }

    public List<Coupon> getCouponsByType(Integer type,Integer id){
        Map<String,Object> query = new HashMap<>();
        query.put("memberId",id);
        query.put("type",type);
        List<Coupon> Coupons =  CouponService.me.getCoupons(query);
        DeleteSome(Coupons);
        return Coupons;
    }

    public void DeleteSome(List<Coupon> Coupons){

        Iterator<Coupon> it = Coupons.iterator();
        while(it.hasNext()){
            Coupon Coupon = it.next();
            // 检查优惠券是否过期，如果过期，则valid置为false
            if(Coupon.getEndtime().getTime() <= (new Date()).getTime()){
                Coupon.setValid(false);
                CouponService.me.update(Coupon);
                it.remove();
            }
        }
    }
}
